package com.sjy.mvvmdemo

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sjy.mvvmdemo.databinding.ActivityMainBinding
import com.sjy.mvvmdemo.main.MainAdapter
import com.sjy.mvvmdemo.main.MainViewModel
import com.sjy.mvvmdemo.main.Person

/**
 * 使用技术：viewModel(liveData) databinding
 * 演示 简单recyclerView显示
 */
class MainActivity : AppCompatActivity() {

    //lateinit表示延迟初始化
    private lateinit var binding: ActivityMainBinding
    private lateinit var mMainViewModel: MainViewModel
    lateinit var adapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater, null, false)
        setContentView(binding.root)
        initViewModel()
        initRecyclerView()

        initFragment()
        initListener()
    }

    /**
     *  使用ViewModel操作数据
     */
    private fun initViewModel() {
        //最新写法 获取和xml交互的对象
        mMainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        //和xml布局绑定
        binding.mMainViewModel = this.mMainViewModel
        //绑定lifecycle
        binding.lifecycleOwner = this
    }

    private fun initFragment() {
    }

    //xml绑定RecyclerView
    private fun initRecyclerView() {
        adapter = MainAdapter()
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter
        adapter.clickListener = View.OnClickListener { view ->
            view?.let {
                Log.d("SJY", "我被点击了")
            }
        }
        showLists()
    }

    private fun initListener() {
        //监听错误提示
        mMainViewModel.msg.observe(this, Observer {
            it?.let {
                Toast.makeText(this, it, Toast.LENGTH_LONG).show()
            }
        })
        //双向绑定，监听xml变化
        mMainViewModel.nameMsg.observe(this, Observer {
            it?.let {
                Log.d("SJY", "输入名字有监听" + it)
            }
        })
        //界面跳转
        binding.btnRoom.setOnClickListener {
            Log.d("SJY", "界面跳转")
            startActivity(Intent(this, SecondActivity::class.java))
            finish()
        }
    }

    //监听MainViewMode数据变化
    private fun showLists() {
        mMainViewModel.listDatas.observe(this, Observer {
            adapter.updateData(it)
        })
    }
}
